<template>
  <el-form ref="form" label-position="left" :model="giteeAccount" label-width="120px" >
    <el-form-item label="私人令牌">
      <el-input type="password" v-model="giteeAccount.access_token"/>
    </el-form-item>
    <el-form-item label="仓库名">
      <el-input :disabled="true" v-model="giteeAccount.repo"/>
    </el-form-item>
  </el-form>
  <el-button @click="validate" v-loading="loading">验证令牌（登录）</el-button>
  <el-button @click="resetGiteeAccount">重置（退出）</el-button>

  <el-divider />

  <el-card class="box-card" v-if="giteeAccount.owner">
    <template #header>
      <div class="card-header">
        <span>当前用户</span>
      </div>
    </template>
    <a :href="giteeAccount.avatar_url" target="_blank"><el-avatar :size="50" :src="giteeAccount.avatar_url" /></a> <span > {{giteeAccount.owner}} </span>
    <el-descriptions :column=1>
      <el-descriptions-item label="个人主页"><a :href="giteeAccount.html_url" target="_blank">{{giteeAccount.html_url}}</a></el-descriptions-item>
      <el-descriptions-item label="仓库地址"><a :href="giteeAccount.html_url + '/' + giteeAccount.repo" target="_blank">{{giteeAccount.html_url + '/' + giteeAccount.repo}}</a></el-descriptions-item>
      <el-descriptions-item label="管理授权"><a :href="GITEE_TOKEN_URL" target="_blank">{{GITEE_TOKEN_URL}}</a></el-descriptions-item>
      <el-descriptions-item label="自动备份"><el-switch v-model="giteeAccount.auto_save" @change="pushGiteeAccount" /></el-descriptions-item>
    </el-descriptions>
  </el-card>
  <el-card v-else>
    使用令牌登录gitee后即可使用自动备份到云端的功能，您记录的数据就更不容易丢失，甚至还能记录历史版本<br/>
    可以在<a :href="GITEE_TOKEN_NEW_URL" target="_blank">{{GITEE_TOKEN_NEW_URL}}</a>生成你的gitee令牌，只需要勾选user_info和projects两项即可<br/>
    在<a :href="GITEE_TOKEN_URL" target="_blank">{{GITEE_TOKEN_URL}}</a>可以取消授权
    <div style="color: red">
      注：使用本功能代表您信任我们的网页，并且我们会尽最大努力保证您的gitee账号安全！
    </div>
  </el-card>

</template>

<script lang="ts" setup>
import { GiteeSettings } from "@/data/entity/GiteeSettings";
import { useAccountStore } from '@/data/stores/account'
import { onMounted, reactive, ref } from "vue";
import { Loading } from "@element-plus/icons-vue";
import { GITEE_TOKEN_URL, GITEE_TOKEN_NEW_URL } from "@/data/constants/Constants";
import * as giteeService from "@/data/service/giteeService";

const accountStore = useAccountStore()

const giteeAccount:GiteeSettings = reactive(new GiteeSettings())
const input = ref('')
const loading = ref(false)

const pullGiteeAccount = () => {
  Object.assign(giteeAccount, accountStore.getGitee())
}

const pushGiteeAccount = () => {
  accountStore.setGitee(giteeAccount)
}

const resetGiteeAccount = () => {
  accountStore.reset()
  pullGiteeAccount()
}

const validate = () => {
  loading.value = true
  pushGiteeAccount()
  giteeService.validateToken().then(()=>{
    pullGiteeAccount()
    loading.value = false
  }).catch(()=>{
    loading.value = false
  })
}


onMounted(()=>{
  pullGiteeAccount()
})

</script>

<style scoped>

</style>